﻿var zombies = zombies || {};

zombies.AddCategory = function () {
    var self = this;
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.IconPath = ko.observable();

    self.CategoryData = {
        Name: self.Name,
        Description: self.Description,
        IconPath: self.IconPath
    }

    self.doAdd = function (formElement) {
        if ($(formElement).valid())
        {
            toastr.info(ko.toJSON(self.CategoryData));
            $.ajax({
                type: "POST",
                url: "/api/AdminApi/PostCategory",
                data: ko.toJSON(self.CategoryData), //Convert the Observable Data into JSON
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                toastr.success('Add Book Successfully !');
                
            }).fail(function () {
                toastr.error('Add Book Failed !');
            });
        }
    }
}

ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length)
                    viewModel.IconPath("D:\\ASP.NET\\Project\\AOS-SourceCode\\Advertising.Client.UI\\App_Data\\Category\\" + $('#upload').prop("files")[0].name);
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    // this uses jquery.form.js plugin
                    $(element.form).ajaxSubmit({
                        url: url,
                        type: "POST",
                        dataType: "json",
                        headers: { "Content-Disposition": "attachment; filename=" + filename },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            // set viewModel property to IconPath
                            bindingContext.$data[property](data);
                            //window.location.replace('http://' + window.location.host + '/admin/listcategory');
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
            });
        }
    }
}


var viewModel;
$(document).ready(function () {

    viewModel = new zombies.AddCategory();

    ko.applyBindings(viewModel);

    //var url = window.location.hostname === 'blueimp.github.io' ?
    //            '//jquery-file-upload.appspot.com/' : 'server/php/';
    //$('#fileupload').fileupload({
    //    url: url,
    //    dataType: 'json',
    //    autoUpload: false,
    //    acceptFileTypes: /(\.|\/)(gif|jpe?g|png|ico)$/i,
    //    maxFileSize: 5000000, // 5 MB
    //    // Enable image resizing, except for Android and Opera,
    //    // which actually support image resizing, but fail to
    //    // send Blob objects via XHR requests:
    //    disableImageResize: /Android(?!.*Chrome)|Opera/
    //        .test(window.navigator.userAgent),
    //    previewMaxWidth: 100,
    //    previewMaxHeight: 100,
    //    previewCrop: true
    //}).on('fileuploadadd', function (e, data) {
    //    data.context = $('<div/>').appendTo('#files');
    //    $.each(data.files, function (index, file) {
    //        var node = $('<p/>')
    //                .append($('<span/>').text(file.name));
    //        if (!index) {
    //            node
    //                .append('<br>');
    //        }
    //        node.appendTo(data.context);
    //    });
    //}).on('fileuploadprocessalways', function (e, data) {
    //    var index = data.index,
    //        file = data.files[index],
    //        node = $(data.context.children()[index]);
    //    if (file.preview) {
    //        node
    //            .prepend('<br>')
    //            .prepend(file.preview);
    //    }
    //    if (file.error) {
    //        node
    //            .append('<br>')
    //            .append($('<span class="text-danger"/>').text(file.error));
    //    }
    //    if (index + 1 === data.files.length) {
    //        data.context.find('button')
    //            .text('Upload')
    //            .prop('disabled', !!data.files.error);
    //    }
    //}).on('fileuploadprogressall', function (e, data) {
    //    var progress = parseInt(data.loaded / data.total * 100, 10);
    //    $('#progress .progress-bar').css(
    //        'width',
    //        progress + '%'
    //    );
    //}).on('fileuploaddone', function (e, data) {
    //    $.each(data.result.files, function (index, file) {
    //        if (file.url) {
    //            var link = $('<a>')
    //                .attr('target', '_blank')
    //                .prop('href', file.url);
    //            $(data.context.children()[index])
    //                .wrap(link);
    //        } else if (file.error) {
    //            var error = $('<span class="text-danger"/>').text(file.error);
    //            $(data.context.children()[index])
    //                .append('<br>')
    //                .append(error);
    //        }
    //    });
    //}).on('fileuploadfail', function (e, data) {
    //    $.each(data.files, function (index, file) {
    //        var error = $('<span class="text-danger"/>').text('File upload failed.');
    //        $(data.context.children()[index])
    //            .append('<br>')
    //            .append(error);
    //    });
    //}).prop('disabled', !$.support.fileInput)
    //    .parent().addClass($.support.fileInput ? undefined : 'disabled');
});